﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using Quartz;
using Rmq.Center;
using User.Api.BizExtensions;
using User.Api.Helpers;
using User.Api.HttpClients;

namespace Out.TaskRunner.QuartzJobs
{
    public class ProcessStopDoctorJob : IJob
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(ProcessStopDoctorJob));

        /// <summary>
        /// 执行成功
        /// </summary>
        public bool IsExecuteSuccess = true;

        /// <summary>
        /// 重试次数
        /// </summary>
        public int RetryTimes = 0;

        public void Execute(IJobExecutionContext context)
        {
            Logger.InfoFormat("Executing job: {0}", context.JobDetail.Key);

            DoTransferDeptAndDoctorInfo();

            while (true)
            {
                if (RetryTimes > 5)
                {
                    IsExecuteSuccess = true;
                    RetryTimes = 0;
                    break;
                }
                
                if (!IsExecuteSuccess)
                {
                    DoTransferDeptAndDoctorInfo();
                }

                RetryTimes++;
            }
        }

        public void DoTransferDeptAndDoctorInfo()
        {
            Console.WriteLine("[{0}] 处理停诊退号退费", DateTime.Now.ToString("MM-dd HH:mm:ss"));

            try
            {
                List<RegInfo> apptOrders = new List<RegInfo>();
                StopDoctorInfo stopInfo;
                using (var ctx = new GdsfybjyWeiXinEntities())
                {
                    var status = ApptOrderExtensions.OrderStatus.取号成功.ToInt32();
                    stopInfo = ctx.StopDoctorInfoes.FirstOrDefault(x => x.state == "0");

                    if (stopInfo != null && String.CompareOrdinal(stopInfo.regDate, DateTime.Today.ToString("yyyy-MM-dd")) >= 0)
                    {
                        apptOrders = (from k in ctx.ApptOrders
                                      join b in ctx.WxUsers on k.WxUserId equals b.Id
                                      where k.OrderStatus == status && k.DeptId == stopInfo.deptId
                                            && k.DoctorId == stopInfo.doctorId
                                            && k.RegDate == stopInfo.regDate
                                            && k.TimeSlice == stopInfo.scheduleId
                                      //&& k.StartTime == stopInfo.beginTime
                                      //&& k.EndTime == stopInfo.endTime
                                      select new RegInfo
                                      {
                                          OrderId = k.Id,
                                          OpenId = b.OpenId,
                                          DoctorName = k.DoctorName,
                                          DeptName = k.DeptName,
                                          CardName = k.CardName,
                                          RegDate = k.RegDate,
                                          SumFee = k.SumFee
                                      }).ToList();
                    }


                    foreach (var apptOrder in apptOrders)
                    {
                        //退号退费
                        if (String.CompareOrdinal(stopInfo.regDate, DateTime.Today.ToString("yyyy-MM-dd")) > 0 && apptOrder.SumFee > 0)
                        {
                            // RMQ 执行退号
                            var unpickupProducer = new OrderUnpickupingProducer();
                            unpickupProducer.Publish(new OrderUnpickupingMsg
                            {
                                OrderType = OrderType.挂号订单,
                                OrderId = apptOrder.OrderId
                            });
                        }

                        //发送模版信息string openId,string deptName,string doctorName,string cardName,string regDate,string sumFee
                        MessageHelper.SendHaltMsg(apptOrder.OpenId,apptOrder.DeptName,apptOrder.DoctorName,apptOrder.CardName,apptOrder.RegDate,apptOrder.SumFee.ToString());
                    }


                    if (stopInfo != null)
                    {
                        stopInfo.state = "1";
                        ctx.SaveChanges();
                    }
                    IsExecuteSuccess = true;
                }
                
                if (IsExecuteSuccess)
                {

                    Console.WriteLine("[{0}] 成功处理停诊退号退费", DateTime.Now.ToString("MM-dd HH:mm:ss"));
                }
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("处理停诊退号退费出错,信息：{0}", JsonConvert.SerializeObject(ex));
            }

        }


        private class RegInfo
        {
            public int OrderId { get; set; }
            public string OpenId { get; set; }
            public string DeptName { get; set; }
            public string DoctorName { get; set; }
            public string CardName { get; set; }
            public string RegDate { get; set; }
            public decimal? SumFee { get; set; }
        }

    }
}
